package com.magold.skill;

import java.util.LinkedList;
import java.util.List;

import org.andengine.engine.handler.IUpdateHandler;

public abstract class BaseSkill implements IUpdateHandler {
	private boolean mLaunching;
	private boolean mEnabled;
	private List<SkillListener> mListeners;
	private List<IUpdateHandler> mUpdateHandlers;

	public BaseSkill() {
		mEnabled = true;
		mListeners = new LinkedList<SkillListener>();
		mUpdateHandlers = new LinkedList<IUpdateHandler>();
	}

	@Override
	public void onUpdate(float pSecondsElapsed) {
		for (IUpdateHandler handler : mUpdateHandlers) {
			handler.onUpdate(pSecondsElapsed);
		}

		if (mEnabled && mLaunching) {
			onSkillLaunching(pSecondsElapsed);
		}
	}
	
	public void registerUpdateHandler(IUpdateHandler pHandler) {
		if (pHandler != null) {
			mUpdateHandlers.add(pHandler);
		}
	}
	
	public void unregisterUpdateHandler(IUpdateHandler pHandler) {
		mUpdateHandlers.remove(pHandler);
	}

	protected abstract void onSkillLaunching(float pSecondsElapsed);

	public void launch() {
		if (!mEnabled || mLaunching) return;

		mLaunching = true;
		
		fire(true);
	}


	public boolean isLaunching() {
		return mLaunching;
	}

	private void fire(boolean pFireLaunch) {
		if (pFireLaunch) {
			for (SkillListener l : mListeners) {
				l.onLaunch(this);
			}
			return;
		}

		for (SkillListener l : mListeners) {
			l.onStop(this);
		}
	}

	public void stop() {
		if (!mLaunching) return;
		
		mLaunching = false;
		
		fire(false);
	}

	public void addSkillListener(SkillListener pListener) {
		mListeners.add(pListener);
	}

	public void removeSkillListener(SkillListener pListener) {
		mListeners.remove(pListener);
	}

	@Override
	public void reset() {
		mListeners.clear();
		mLaunching = false;
	}

	public void setEnabled(boolean pEnabled) {
		if (mEnabled && !pEnabled) {
			stop();
		}

		mEnabled = pEnabled;
	}

	public static interface SkillListener {
		public void onLaunch(BaseSkill pSkill);
		public void onStop(BaseSkill pSkill);
	}

}
